//
//  LoginViewController.swift
//  LaiLang
//
//  Created by David on 2017/2/4.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit

class LoginViewController: UIViewController {

    var scrollView: UIScrollView!
    
    var loginMenu: LoginMenuView!
    var loginView: LoginView!
    var regView: RegView!
    
    var backBtn: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        let image = UIImage(contentsOfFile: Bundle.main.path(forResource: "loginimg", ofType: "png")!)!
        let ivHeight = image.size.height * view.bounds.width / image.size.width
        let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: ivHeight))
        imageView.image = image
        view.addSubview(imageView)
        
        
        
        // Do any additional setup after loading the view.
        scrollView = UIScrollView(frame: CGRect(x: 0, y: ivHeight, width: view.bounds.width, height: view.bounds.height - ivHeight))
        scrollView.isScrollEnabled = false
        scrollView.contentSize = CGSize(width: view.bounds.width*2, height: scrollView.bounds.height)
        scrollView.backgroundColor = UIColor(hex: 0xf7f9fa)
        view.addSubview(scrollView)
        
        loginMenu = LoginMenuView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: scrollView.bounds.height))
        scrollView.addSubview(loginMenu)
        loginMenu.regBtn.addTarget(self, action: #selector(LoginViewController.gotoReg), for: .touchUpInside)
        loginMenu.weiboLoginBtn.addTarget(self, action: #selector(LoginViewController.gotoWBLogin), for: .touchUpInside)
        loginMenu.wxLoginBtn.addTarget(self, action: #selector(LoginViewController.gotoWXLogin), for: .touchUpInside)
        loginMenu.loginBtn.addTarget(self, action: #selector(LoginViewController.gotoLogin), for: .touchUpInside)
        
        loginView = LoginView(frame: CGRect(x: view.bounds.width, y: 0, width: view.bounds.width, height: scrollView.bounds.height))
        scrollView.addSubview(loginView)
        loginView.passwordInput.input.addTarget(self, action: #selector(LoginViewController.LLogin), for: .editingDidEndOnExit)
        loginView.submitBtn.addTarget(self, action: #selector(LoginViewController.LLogin), for: .touchUpInside)
        
        regView = RegView(frame: CGRect(x: view.bounds.width, y: 0, width: view.bounds.width, height: scrollView.bounds.height))
        scrollView.addSubview(regView)
        regView.passwordInput.input.addTarget(self, action: #selector(LoginViewController.LLRegister), for: .editingDidEndOnExit)
        regView.submitBtn.addTarget(self, action: #selector(LoginViewController.LLRegister), for: .touchUpInside)
        
        backBtn = UIButton(frame: CGRect(x: 16, y: 36, width: 24, height: 24))
        backBtn.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi)/2)
        backBtn.setTitle("\u{e61f}", for: .normal)
        backBtn.setTitleColor(UIColor.black, for: .normal)
        backBtn.titleLabel?.font = UIFont(name: "iconfont", size: 24)
        view.addSubview(backBtn)
        backBtn.alpha = 0
        backBtn.addTarget(self, action: #selector(LoginViewController.goBack), for: .touchUpInside)
    }
    
    func gotoLogin(){
        loginView.alpha = 1
        regView.alpha = 0
        
        scrollView.setContentOffset(CGPoint(x: view.bounds.width, y: 0), animated: true)
        
        UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseInOut, animations: {
//            self.backBtn.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI)/2)
            self.backBtn.alpha = 1
        }, completion: nil)
    }
    
    func gotoReg(){
        loginView.alpha = 0
        regView.alpha = 1
        
        scrollView.setContentOffset(CGPoint(x: view.bounds.width, y: 0), animated: true)
        
        UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseInOut, animations: {
//            self.backBtn.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI)/2)
            self.backBtn.alpha = 1
        }, completion: nil)
    }
    
    func goBack(){
        if scrollView.contentOffset.x == 0{
//            dismiss(animated: true, completion: nil)
        }else{
            
            loginView.phoneInput.input.resignFirstResponder()
            loginView.passwordInput.input.resignFirstResponder()
            regView.phoneInput.input.resignFirstResponder()
            regView.verifyInput.input.resignFirstResponder()
            regView.passwordInput.input.resignFirstResponder()
            
            scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: true)
            
            UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseInOut, animations: {
//                self.backBtn.transform = CGAffineTransform(rotationAngle: 0)
                self.backBtn.alpha = 0
            }, completion: nil)
        }
        
    }
    
    func gotoWBLogin(){
        print("gotoWBLogin")
        // TODO: 微博登陆
        
        
    }
    
    func gotoWXLogin(){
        print("gotoWXLogin")
        // TODO: 微信登陆
    }
    
    func LLogin(){
        loginView.phoneInput.input.resignFirstResponder()
        loginView.passwordInput.input.resignFirstResponder()
        if loginView.checkInput() {
            loginView.setPostState(state: true)
            print("normalLogin")
            // TODO: 直接登陆
            var resq = URLRequest(url: URL(string: "\(HJY_DOMAIN_NAME)api/user/login")!)
            resq.httpMethod = "POST"
            resq.httpBody = "phone=\(loginView.phoneInput.input.text!)&password=\(loginView.passwordInput.input.text!)".data(using: .utf8)
            URLSession.shared.dataTask(with: resq, completionHandler: { (data, _, err) in
                do{
                    if err != nil{
                        throw err!
                        
                    }
                    print(String(data: data!, encoding: .utf8) ?? "data nil" )
                    
                    let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                    
                    let token = jsonObj?.object(forKey: "token") as? String
                    if token != nil{
                        UserDefaults.standard.set(token!, forKey: "token")
                        DispatchQueue.main.async {
                            self.jumpToUserPage()
                        }
                    }else{
                        DispatchQueue.main.async {
                            let alert = UIAlertController(title: "token获取失败", message: nil, preferredStyle: .alert)
                            alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                            self.present(alert, animated: true, completion: nil)
                            self.loginView.setPostState(state: false)
                        }
                    }
                    
                    
                }catch let ex{
                    print(ex)
                    DispatchQueue.main.async {
                        let alert = UIAlertController(title: "请求出错", message: nil, preferredStyle: .alert)
                        alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                        self.present(alert, animated: true, completion: nil)
                        self.loginView.setPostState(state: false)
                    }
                }
            }).resume()
            
        }
    }
    
    func LLRegister(){
        regView.phoneInput.input.resignFirstResponder()
        regView.verifyInput.input.resignFirstResponder()
        regView.passwordInput.input.resignFirstResponder()
        if regView.checkInput(){
            regView.setPostState(state: true)
            print("phoneReg")
            // TODO: 手机注册
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func jumpToUserPage(){
        var vcs = tabBarController?.viewControllers
        vcs?.removeLast()
        let userVC = UserViewController()
        userVC.tabBarItem = UITabBarItem(title: "我", image: #imageLiteral(resourceName: "wode"), tag: 3)
        vcs?.append(UINavigationController(rootViewController: userVC))
        if vcs != nil {
            tabBarController?.setViewControllers(vcs, animated: false)
        }
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

class LoginMenuView: UIView{
    
    var regBtn: UIButton!
    var weiboLoginBtn: UIButton!
    var wxLoginBtn: UIButton!
    var loginBtn: UIButton!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        
        regBtn = UIButton(frame: CGRect(x: 64, y: 128, width: bounds.width - 128, height: 44))
        regBtn.setTitleColor(UIColor.white, for: .normal)
        regBtn.backgroundColor = themeColor
        regBtn.layer.cornerRadius = 4
        regBtn.setTitle("手机注册", for: .normal)
        regBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        addSubview(regBtn)
        
        
        weiboLoginBtn = UIButton(frame: CGRect(x: 64, y: 128 + 44 + 8, width: bounds.width - 128, height: 44))
        weiboLoginBtn.backgroundColor = UIColor.white
        weiboLoginBtn.layer.cornerRadius = 4
        
        var attrStr = NSMutableAttributedString(string: "\u{e64b} 微博登陆")
        attrStr.addAttribute(NSFontAttributeName, value: UIFont(name: "iconfont", size: 16)!, range: NSMakeRange(0, 1))
        attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: NSMakeRange(0, 1))
        attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor(r: 120, g: 120, b: 120), range: NSMakeRange(2, 4))
        attrStr.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 14), range: NSMakeRange(2, 4))
        weiboLoginBtn.setAttributedTitle(attrStr, for: .normal)
        addSubview(weiboLoginBtn)
        
        
        wxLoginBtn = UIButton(frame: CGRect(x: 64, y: 128 + 44 + 8 + 44 + 8, width: bounds.width - 128, height: 44))
        wxLoginBtn.backgroundColor = UIColor.white
        wxLoginBtn.layer.cornerRadius = 4
        attrStr = NSMutableAttributedString(string: "\u{e691} 微信登陆")
        attrStr.addAttribute(NSFontAttributeName, value: UIFont(name: "iconfont", size: 16)!, range: NSMakeRange(0, 1))
        
        attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor(r: 24, g: 167, b: 15), range: NSMakeRange(0, 1))
        attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor(r: 120, g: 120, b: 120), range: NSMakeRange(2, 4))
        attrStr.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 14), range: NSMakeRange(2, 4))
        wxLoginBtn.setAttributedTitle(attrStr, for: .normal)
        addSubview(wxLoginBtn)
        
        loginBtn = UIButton(frame: CGRect(x: 0, y: bounds.height - 128, width: 128, height: 20))
        loginBtn.center.x = center.x
        loginBtn.setTitle("已有账号在此登录 > ", for: .normal)
        loginBtn.setTitleColor(UIColor.lightGray, for: .normal)
        loginBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        addSubview(loginBtn)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class LoginView: UIView{
    
    var scrollView: UIScrollView!
    
    var phoneInput: LLoginInput!
    var passwordInput: LLoginInput!
    var submitBtn: UIButton!
    
    var errMsg: UILabel!
    
    var loadingView: LLFullScreenLoading!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: frame.width, height: frame.height))
        scrollView.alwaysBounceVertical = true
        scrollView.keyboardDismissMode = .onDrag
        addSubview(scrollView)
        
        phoneInput = LLoginInput(frame: CGRect(x: 16, y: 128, width: frame.width - 32, height: 44), type: .phone)
        scrollView.addSubview(phoneInput)
        phoneInput.maxLength = 11
        
        passwordInput = LLoginInput(frame: CGRect(x: 16, y: 128 + 44 + 16, width: frame.width - 32, height: 44), type: .password)
        scrollView.addSubview(passwordInput)
        passwordInput.maxLength = 20
        
        submitBtn = UIButton(frame: CGRect(x: 0, y: 128 + 44 + 16 + 44 + 64, width: 128, height: 44))
        submitBtn.center.x = frame.width/2
        submitBtn.setTitle("登陆", for: .normal)
        submitBtn.setTitleColor(UIColor.white, for: .normal)
        submitBtn.backgroundColor = themeColor
        submitBtn.layer.cornerRadius = 22
        scrollView.addSubview(submitBtn)
        
        errMsg = UILabel(frame: CGRect(x: 16, y: 64, width: frame.width - 32, height: 64))
        errMsg.font = UIFont.systemFont(ofSize: 14)
        errMsg.textColor = UIColor.red
        errMsg.textAlignment = .center
        errMsg.numberOfLines = 0
        errMsg.alpha = 0
        scrollView.addSubview(errMsg)
        
        loadingView = LLFullScreenLoading(frame: CGRect(x: 0, y: 0, width: frame.width, height: frame.height))
        addSubview(loadingView)
        loadingView.alpha = 0
    }
    
    func checkInput() ->Bool{
        let phone = phoneInput.input.text
        if phone == nil {
            return false
        }
        let regex = try? NSRegularExpression(pattern: "1[0-9]{10}", options: .caseInsensitive)
        if regex == nil{
            return false
        }
        let res = regex!.matches(in: phone!, options: .withoutAnchoringBounds, range: NSMakeRange(0, phone!.characters.count))
        if res.count == 0{
            showError(text: "手机号格式不对")
            phoneInput.input.becomeFirstResponder()
            return false
        }
        
        let psw = passwordInput.input.text
        if psw == nil {
            return false
        }
        if psw!.characters.count < 6{
            showError(text: "密码长度不足")
            passwordInput.input.becomeFirstResponder()
            return false
        }
        return true
    }
    
    func setPostState(state: Bool){
        loadingView.alpha = state ? 1.0 : 0.0
    }
    
    func showError(text: String?){
        if text != nil {
            if text! != "" {
                errMsg.text = text
                
                if errMsg.alpha == 0{
                    self.errMsg.center.y += 20
                    errMsg.alpha = 0
                    UIView.animate(withDuration: 0.1, delay: 0, options: .curveEaseOut, animations: {
                        self.errMsg.center.y -= 24
                        self.errMsg.alpha = 1
                    }, completion: nil)
                    UIView.animate(withDuration: 0.1, delay: 0.1, options: .curveEaseIn, animations: {
                        self.errMsg.center.y += 4
                    }, completion: nil)
                    UIView.animate(withDuration: 0.2, delay: 3, options: .curveEaseInOut, animations: {
                        self.errMsg.center.y += 20
                        self.errMsg.alpha = 0
                    }, completion: { (finish) in
                        self.errMsg.center.y -= 20
                    })
                    
                }
            }
        }
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class RegView: UIView{
    var scrollView: UIScrollView!
    
    var phoneInput: LLoginInput!
    var verifyInput: LLoginInput!
    var getVerifyBtn: UIButton!
    var passwordInput: LLoginInput!
    var submitBtn: UIButton!
    
    var errMsg: UILabel!
    
    var countDown = 60
    
    var loadingView: LLFullScreenLoading!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: frame.width, height: frame.height))
        scrollView.alwaysBounceVertical = true
        scrollView.keyboardDismissMode = .onDrag
        addSubview(scrollView)
        
        phoneInput = LLoginInput(frame: CGRect(x: 16, y: 128, width: frame.width - 32, height: 44), type: .phone)
        scrollView.addSubview(phoneInput)
        phoneInput.maxLength = 11
        
        verifyInput = LLoginInput(frame: CGRect(x: 16, y: 128 + 44 + 16, width: frame.width - 32 - 128 - 8, height: 44), type: .verify)
        scrollView.addSubview(verifyInput)
        verifyInput.maxLength = verifyLength
        
        getVerifyBtn = UIButton(frame: CGRect(x: verifyInput.frame.width + 16 + 8, y: 128 + 44 + 16, width: 128, height: 44))
        getVerifyBtn.setTitle("获取验证码", for: .normal)
        getVerifyBtn.setTitleColor(loginThemeColor, for: .normal)
        getVerifyBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        scrollView.addSubview(getVerifyBtn)
        getVerifyBtn.addTarget(self, action: #selector(RegView.LLGetVerify), for: .touchUpInside)
        
        passwordInput = LLoginInput(frame: CGRect(x: 16, y: 128 + 44 + 16 + 44 + 16, width: frame.width - 32, height: 44), type: .password)
        scrollView.addSubview(passwordInput)
        passwordInput.maxLength = passwordLengthMax
        
        submitBtn = UIButton(frame: CGRect(x: 0, y: 128 + 44 + 16 + 44 + 16 + 64, width: 128, height: 44))
        submitBtn.center.x = frame.width/2
        submitBtn.setTitle("下一步", for: .normal)
        submitBtn.setTitleColor(UIColor.white, for: .normal)
        submitBtn.backgroundColor = themeColor
        submitBtn.layer.cornerRadius = 22
        scrollView.addSubview(submitBtn)
        
        errMsg = UILabel(frame: CGRect(x: 16, y: 64, width: frame.width - 32, height: 64))
        errMsg.font = UIFont.systemFont(ofSize: 14)
        errMsg.textColor = UIColor.red
        errMsg.textAlignment = .center
        errMsg.numberOfLines = 0
        errMsg.alpha = 0
        scrollView.addSubview(errMsg)
        
        loadingView = LLFullScreenLoading(frame: CGRect(x: 0, y: 0, width: frame.width, height: frame.height))
        addSubview(loadingView)
        loadingView.alpha = 0
        
        Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(RegView.timer), userInfo: nil, repeats: true)
        let lastDateString = UserDefaults.standard.object(forKey: LLVerifyDurationKey) as? String
        if lastDateString != nil {
            let format = DateFormatter()
            format.dateFormat = dateFormat
            let lastDate = format.date(from: lastDateString!)
            if lastDate != nil {
                let duration = Date().timeIntervalSince(lastDate!)
                if duration < 60 && duration > 0{
                    getVerifyBtn.setTitleColor(UIColor.lightGray, for: .normal)
                    getVerifyBtn.isEnabled = false
                    countDown = 60 - Int(duration)
                }
            }
        }
    }
    
    func LLGetVerify(){
        if checkVerifyInput() {
            getVerifyBtn.setTitleColor(UIColor.lightGray, for: .normal)
            getVerifyBtn.isEnabled = false
            countDown = 59
            let format = DateFormatter()
            format.dateFormat = dateFormat
            UserDefaults.standard.set(format.string(from: Date()), forKey: LLVerifyDurationKey)
            
            print("获取验证码")
            
            //TODO: 获取验证码
//            var resq = URLRequest(url: URL(string: "")!)
//            resq.httpMethod = "POST"
//            resq.httpBody = "".data(using: .utf8)
//            
        }
    }
    
    func timer(){
        if countDown < 60 && countDown > 0 {
            countDown -= 1
            getVerifyBtn.setTitle("获取验证码(\(countDown))", for: .normal)
            
        }
        if countDown == 0{
            getVerifyBtn.setTitle("获取验证码", for: .normal)
            getVerifyBtn.setTitleColor(loginThemeColor, for: .normal)
            getVerifyBtn.isEnabled = true
        }
    }
    
    func checkVerifyInput() ->Bool {
        let phone = phoneInput.input.text
        if phone == nil {
            return false
        }
        let regex = try? NSRegularExpression(pattern: "1[0-9]{10}", options: .caseInsensitive)
        if regex == nil{
            return false
        }
        let res = regex!.matches(in: phone!, options: .withoutAnchoringBounds, range: NSMakeRange(0, phone!.characters.count))
        if res.count == 0{
            showError(text: "手机号格式不对")
            phoneInput.input.becomeFirstResponder()
            return false
        }
        return true
    }
    
    func checkInput() ->Bool{
        let phone = phoneInput.input.text
        if phone == nil {
            return false
        }
        let regex = try? NSRegularExpression(pattern: "1[0-9]{10}", options: .caseInsensitive)
        if regex == nil{
            return false
        }
        let res = regex!.matches(in: phone!, options: .withoutAnchoringBounds, range: NSMakeRange(0, phone!.characters.count))
        if res.count == 0{
            showError(text: "手机号格式不对")
            phoneInput.input.becomeFirstResponder()
            return false
        }
        
        let verify = verifyInput.input.text
        if verify == nil {
            return false
        }
        
        if verify!.characters.count < verifyLength{
            showError(text: "验证码长度不足")
            verifyInput.input.becomeFirstResponder()
            return false
        }
        
        let psw = passwordInput.input.text
        if psw == nil {
            return false
        }
        if psw!.characters.count < passwordLegthMin{
            showError(text: "密码长度不足")
            passwordInput.input.becomeFirstResponder()
            return false
        }
        return true
    }
    
    func setPostState(state: Bool){
        loadingView.alpha = state ? 1.0 : 0.0
    }
    
    func showError(text: String?){
        if text != nil {
            if text! != "" {
                errMsg.text = text
                
                if errMsg.alpha == 0{
                    self.errMsg.center.y += 20
                    errMsg.alpha = 0
                    UIView.animate(withDuration: 0.1, delay: 0, options: .curveEaseOut, animations: {
                        self.errMsg.center.y -= 24
                        self.errMsg.alpha = 1
                    }, completion: nil)
                    UIView.animate(withDuration: 0.1, delay: 0.1, options: .curveEaseIn, animations: {
                        self.errMsg.center.y += 4
                    }, completion: nil)
                    UIView.animate(withDuration: 0.2, delay: 3, options: .curveEaseInOut, animations: {
                        self.errMsg.center.y += 20
                        self.errMsg.alpha = 0
                    }, completion: { (finish) in
                        self.errMsg.center.y -= 20
                    })
                    
                }
            }
        }
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
